package com.wolfking.converter.transform.extend;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.wolfking.converter.transform.AbstractExtendTransform;
import com.wolfking.converter.util.CaesarUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

@Slf4j
public class JsonExtractDictTransform extends AbstractExtendTransform<String> {


    private Config config;

    public JsonExtractDictTransform() {
    }


    public JsonExtractDictTransform(String path) {
        config = new Gson().fromJson(path, Config.class);
    }

    @Override
    public String transform(Object value) {
        if (Objects.isNull(value)) {
            return config.getDefaultValue();
        }
        String beforeValue;
        if (value instanceof String) {
            beforeValue = value.toString();
        } else if (value instanceof byte[]) {
            beforeValue = new String((byte[]) value, StandardCharsets.UTF_8);
        } else {
            beforeValue = value.toString();
        }
        if (StringUtils.isBlank(beforeValue)) {
            return config.getDefaultValue();
        }

        if (CaesarUtil.isEncrypted(beforeValue)) {
            beforeValue = CaesarUtil.decode(beforeValue);
        }
        try {
            String dictValue = "";
            JsonElement element = JsonParser.parseString(beforeValue);
            if (element.isJsonArray() || element.isJsonObject()) {
                dictValue = JsonExtractTransform.extractStringOne(element, config.getPath());
            }
            if (StringUtils.isNotBlank(dictValue)) {
                if (StringUtils.isNotBlank(config.getDict())) {
                    return new DictTransform(config.getDict()).transform(dictValue);
                } else {
                    return dictValue;
                }
            }
            return config.getDefaultValue();
        } catch (Exception e) {
            log.warn("", e);
            return config.getDefaultValue();
        }
    }

    @Override
    public String getExampleConfig() {
        return "{\n" +
                "\t\"path\": \"路径\",\n" +
                "\t\"dict\": \"字典type\",\n" +
                "\t\"defaultValue\": \"默认值\"\n" +
                "}";
    }

    @Override
    public String getExampleConfigDesc() {
        return "{\n" +
                "\t\"path\": \"a.b.c\",\n" +
                "\t\"dict\": \"boolean\",\n" +
                "\t\"defaultValue\": \"否\"\n" +
                "}";
    }

    @Data
    private static class Config {
        private String path;

        private String dict;

        private String defaultValue = "";
    }
}
